
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

import '../entity/current_task_entity.dart';
import '../main.dart';
import '../mqtt/mqtt.dart';

class HttpHelper{
  static HttpHelper get instance => _getInstance();

  static HttpHelper? _httpHelper;

  static HttpHelper _getInstance() {
    _httpHelper ??= HttpHelper();
    return _httpHelper!;
  }

  late Dio _dio;

  HttpHelper() {

    _dio = Dio();
    _dio.options.connectTimeout = const Duration(seconds: 5);
    _dio.options.receiveTimeout = const Duration(seconds: 10);
    // PrettyDioLogger log = PrettyDioLogger(
    //     requestHeader: true,
    //     requestBody: true,
    //     responseBody: true,
    //     responseHeader: false,
    //     error: true,
    //     compact: true,
    //     maxWidth: 90);
    // _dio.interceptors.add(log);

  }


  Future downLoad(String url, {Object? data,Options? options }) async {
    Response response;
    try{
      var td = await getExternalStorageDirectory();
      String directoryPath = '${td!.path}/img';

      var downloadUrl = '';
      if(url.endsWith('jpg')){
        downloadUrl = '${td.path}/img/${DateTime.now().millisecondsSinceEpoch}.jpg';
      }
      if(url.endsWith('png')){
        downloadUrl = '${td.path}/img/${DateTime.now().millisecondsSinceEpoch}.png';
      }
      if(url.endsWith('mp4')){
        downloadUrl = '${td.path}/img/${DateTime.now().millisecondsSinceEpoch}.mp4';
      }

      response = await _dio.download(url,downloadUrl,onReceiveProgress: (int count, int total){
        if (total != -1) {
          print('totle = $total, count = $count');
          if(total == count){
            // const MethodChannel('toAndroid').invokeMethod('install',{'message':downloadUrl});
            // webSocketHelper.add(updated());
          }
        }
      });

    }on DioException catch(e){
      if(e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.connectionError){
        return {'code': 505,};
      }
      return e.response!.data;
    }
    return response.data;
  }



  Future downLoadApk(String url, {Object? data,Options? options }) async {
    Response response;
    try{
      var td = await getExternalStorageDirectory();
      String directoryPath = '${td!.path}/apk';
      var downloadUrl = '${td.path}/apk/${DateTime.now().millisecondsSinceEpoch}.apk';

      response = await _dio.download(url,downloadUrl,onReceiveProgress: (int count, int total){
        if (total != -1) {
          print('totle = $total, count = $count');
          if(total == count){
            Future.delayed(const Duration(seconds: 3),(){
              const MethodChannel('toAndroid').invokeMethod('install',{'message':downloadUrl});
              mqttHelper.push(update(uuid: currentTask.uuids[Task.update], trade_no: currentTask.tradeNos[Task.update], version: currentTask.updateVersion, state: '4'));
            });

          }
        }
      });

    }on DioException catch(e){
      if(e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout || e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.connectionError){
        return {'code': 505,};
      }
      return e.response!.data;
    }
    return response.data;
  }

}